require File.dirname(__FILE__) + '/../Common/settings.rb'
require File.dirname(__FILE__) + '/../Common/RightAPI.rb'

class EBSSnapshot

  def initialize(timeout = 300, api = RightAPI.new)
    @api = api
    @api.log = true
    @api.login(:username => USERNAME, :password => PASSWORD, :account => ACCOUNT)
    @timeout = timeout
  end

  def send_create_snapshot(nickname, description, volume_id)
    current_time   = Time.now
    formatted_time = "#{current_time.year}#{current_time.month}#{current_time.day}-#{current_time.hour}:#{current_time.min}:#{current_time.sec}"

    params = {
        'ec2_ebs_snapshot[nickname]'          => "#{nickname} #{formatted_time}",
        'ec2_ebs_snapshot[description]'       => "#{description} #{formatted_time}",
        'ec2_ebs_snapshot[ec2_ebs_volume_id]' => volume_id,
        'ec2_ebs_snapshot[commit_state]'      => "implicit"
    }

    @api.send("ec2_ebs_snapshots", "post", params)
  end

  def create_snapshot(nickname, description, volume_id)
    send_create_snapshot(nickname, description, volume_id)
    code = @api.headers[:status]
    raise "error creating snapshot for volume: #{volume_id}, code: #{code}" unless code == "201"
    id = snapshot_id()
    sleep_until_completed(id)
    id
  end

  def sleep_until_completed(snapshot_id)
    completed = false
    elapsed = 0
    until completed || elapsed >= @timeout
      elapsed += 5
      result = get_snapshot snapshot_id
      completed = result.include? "<aws-status>completed</aws-status>"
      return if completed
      puts "sleeping for 5 seconds, elapsed: #{elapsed}"
      sleep 5
    end
    raise "time out error, snapshot did not complete on time"
  end

  def get_snapshot(snapshot_id)
    @api.send "ec2_ebs_snapshots/#{snapshot_id}"
  end

  def snapshot_id
    @api.headers[:location].split("/").last
  end

end